package top.boycharse.blog.secruity;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import top.boycharse.blog.secruity.filter.JwtAuthenticateFilter;
import top.boycharse.blog.secruity.filter.JwtAuthorizationFilter;
import top.boycharse.blog.secruity.handler.DeniedHandler;
import top.boycharse.blog.secruity.handler.FailHandler;

@Configuration
public class WebSecruityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .and()
                .authorizeRequests()
                .antMatchers("/manager/**").hasAuthority("admin")
                .anyRequest()
                .permitAll()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new DeniedHandler())
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint());

        http.addFilterAt(jwtAuthenticateFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterAt(jwtAuthorizationFilter(), BasicAuthenticationFilter.class);
    }

    @Bean
    public JwtAuthenticateFilter jwtAuthenticateFilter() throws Exception{
        JwtAuthenticateFilter filter = new JwtAuthenticateFilter();
        filter.setFilterProcessesUrl("/doLogin");
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationFailureHandler(new FailHandler());

        return filter;
    }

    @Bean
    public JwtAuthorizationFilter jwtAuthorizationFilter() throws Exception{
        JwtAuthorizationFilter filter = new JwtAuthorizationFilter(authenticationManager());
        return filter;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
